package com.aizuda.boot.modules.flw.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aizuda.boot.modules.business.contract.entity.*;
import com.aizuda.boot.modules.business.contract.entity.dto.WorkflowModuleDTO;
import com.aizuda.boot.modules.common.constant.enums.DisplayTypeEnum;
import com.aizuda.boot.modules.common.constant.enums.FieldTypeEnum;
import com.aizuda.boot.modules.business.contract.entity.vo.FieldTreeDTO;
import com.aizuda.boot.modules.business.contract.entity.vo.WorkflowFormFieldsListDTO;
import com.aizuda.boot.modules.business.contract.entity.vo.WorkflowFormFieldDTO;
import com.aizuda.boot.modules.business.contract.mapper.*;
import com.aizuda.boot.modules.flw.entity.FlwFormTemplate;
import com.aizuda.boot.modules.flw.entity.vo.FlwFormTemplateDetailVO;
import com.aizuda.boot.modules.flw.mapper.FlwFormTemplateMapper;
import com.aizuda.boot.modules.flw.service.IFlwFormTemplateService;
import com.aizuda.common.toolkit.CollectionUtils;
import com.aizuda.common.toolkit.JacksonUtils;
import com.aizuda.core.api.ApiAssert;
import com.aizuda.service.service.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.Comparator;

/**
 * 流程表单模板 服务实现类
 *
 * @author hubin
 * @since 2024-05-19
 */
@Service
public class FlwFormTemplateServiceImpl extends BaseServiceImpl<FlwFormTemplateMapper, FlwFormTemplate> implements IFlwFormTemplateService {

    @Resource
    private ContractWorkflowFormFieldMapper contractWorkflowFormFieldMapper;

    @Resource
    private ContractWorkflowModuleMapper contractWorkflowModuleMapper;

    @Resource
    private ContractModuleMapper contractModuleMapper;

    @Resource
    private ContractFieldMapper contractFieldMapper;

    @Resource
    private ContractModuleFieldMapper contractModuleFieldMapper;

    @Override
    public Page<FlwFormTemplate> page(Page<FlwFormTemplate> page, FlwFormTemplate flwFormTemplate) {
        LambdaQueryWrapper<FlwFormTemplate> lqw = Wrappers.lambdaQuery(flwFormTemplate);
        lqw.orderByDesc(FlwFormTemplate::getCreateTime);
        return super.page(page, lqw);
    }


    @Override
    public Page<FlwFormTemplate> pageSimple(Page<FlwFormTemplate> page, FlwFormTemplate flwFormTemplate) {
        if (null == flwFormTemplate) {
            flwFormTemplate = new FlwFormTemplate();
        }
        flwFormTemplate.setStatus(1);
        LambdaQueryWrapper<FlwFormTemplate> lqw = Wrappers.lambdaQuery(flwFormTemplate);
        lqw.select(FlwFormTemplate::getId, FlwFormTemplate::getName, FlwFormTemplate::getCode);
        lqw.orderByDesc(FlwFormTemplate::getCreateTime);
        return super.page(page, lqw);
    }


    @Override
    public boolean updateById(FlwFormTemplate flwFormTemplate) {
        ApiAssert.fail(null == flwFormTemplate.getId(), "主键不存在无法更新");
        return super.updateById(flwFormTemplate);
    }

    @Override
    public boolean removeNotBindByIds(List<Long> ids) {
        return super.remove(Wrappers.<FlwFormTemplate>lambdaQuery().in(FlwFormTemplate::getId, ids)
                .ne(FlwFormTemplate::getStatus, 3));
    }

    @Override
    public boolean existByFormCategoryIds(List<Long> formCategoryIds) {
        return lambdaQuery().in(FlwFormTemplate::getFormCategoryId, formCategoryIds).count() > 0;
    }

    @Override
    public FlwFormTemplate getByConfigure(String configureProcessForm) {
        Long id = null;
        if (null != configureProcessForm) {
            // 加载表单模板内容
            Map<String, Object> formMap = JacksonUtils.readMap(configureProcessForm);
            if (null != formMap) {
                String formId = (String) formMap.get("formId");
                if (null != formId) {
                    id = Long.valueOf(formId);
                }
            }
        }
        ApiAssert.fail(null == id, "业务表单配置内容有误");
        FlwFormTemplate flwFormTemplate = this.checkById(id);
        if (null != flwFormTemplate && !Objects.equals(3, flwFormTemplate.getStatus())) {
            // 加载设置为绑定状态，该状态不允许删除，只能修改编辑
            FlwFormTemplate temp = new FlwFormTemplate();
            temp.setStatus(3);
            temp.setId(flwFormTemplate.getId());
            super.updateById(temp);
        }
        return flwFormTemplate;
    }

    @Override
    public boolean updateStatusById(Long id, Integer status) {
        FlwFormTemplate flwFormTemplate = new FlwFormTemplate();
        flwFormTemplate.setId(id);
        flwFormTemplate.setStatus(Objects.equals(status, 1) ? 1 : 0);
        return super.updateById(flwFormTemplate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveNew(FlwFormTemplate flwFormTemplate) {
        boolean save = this.save(flwFormTemplate);
//        if (save) {
//            Long id = flwFormTemplate.getId();
//            this.initField(id);
//        }
        return flwFormTemplate.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeNotBindByIdsNew(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return true;
        }
//        List<Long> templateIds = this.list(Wrappers.<FlwFormTemplate>lambdaQuery().in(FlwFormTemplate::getId, ids)
//                        .ne(FlwFormTemplate::getStatus, 3).select(FlwFormTemplate::getId))
//                .stream().map(FlwFormTemplate::getId).collect(Collectors.toList());
        contractWorkflowModuleMapper.delete(Wrappers.<ContractWorkflowModuleEntity>lambdaQuery()
                .in(ContractWorkflowModuleEntity::getWorkflowId, ids));
        contractWorkflowFormFieldMapper.delete(Wrappers.<ContractWorkflowFormFieldEntity>lambdaQuery()
                .in(ContractWorkflowFormFieldEntity::getWorkflowId, ids));
        return super.remove(Wrappers.<FlwFormTemplate>lambdaQuery().in(FlwFormTemplate::getId, ids));
    }

    @Override
    public FlwFormTemplateDetailVO getByIdNew(Long id) {
        // 数据校验
        if (null == id) {
            return systemField();
        }
        FlwFormTemplate template = this.getById(id);
        ApiAssert.fail(null == template, "流程表单模板不存在");
        FlwFormTemplateDetailVO result = new FlwFormTemplateDetailVO();
        // 赋值基本信息
        BeanUtils.copyProperties(template, result);

        // 查询全部模块
        List<ContractModuleEntity> moduleEntities = contractModuleMapper.selectList(new LambdaQueryWrapper<ContractModuleEntity>()
                .eq(ContractModuleEntity::getIsEnabled, true));
        List<Integer> moduleIds = moduleEntities.stream().map(ContractModuleEntity::getId).collect(Collectors.toList());

        // 查询全部模块下字段
        List<ContractModuleFieldEntity> moduleFieldEntities = contractModuleFieldMapper.selectList(new LambdaQueryWrapper<ContractModuleFieldEntity>()
                .in(ContractModuleFieldEntity::getModuleId, moduleIds));

        // 查询启用的模块
        List<Integer> enabledModuleIds = contractWorkflowModuleMapper.selectList(new LambdaQueryWrapper<ContractWorkflowModuleEntity>()
                        .eq(ContractWorkflowModuleEntity::getWorkflowId, id))
                .stream().map(ContractWorkflowModuleEntity::getModuleId).collect(Collectors.toList());

        // 查询启用的字段
        List<ContractWorkflowFormFieldEntity> enabledFields = contractWorkflowFormFieldMapper.selectList(new LambdaQueryWrapper<ContractWorkflowFormFieldEntity>()
                .eq(ContractWorkflowFormFieldEntity::getWorkflowId, id));

        // 查询所有字段详情
        List<Long> allFieldIds = moduleFieldEntities.stream().map(ContractModuleFieldEntity::getFieldId).distinct().collect(Collectors.toList());
        List<ContractFieldEntity> allFields = contractFieldMapper.selectList(new LambdaQueryWrapper<ContractFieldEntity>()
                .in(ContractFieldEntity::getId, allFieldIds)
                .eq(ContractFieldEntity::getIsEnabled, true));

        // 构造结果
        result.setFormFields(buildFormFields(moduleEntities, enabledModuleIds, allFields, enabledFields));



        return result;
    }

    private FlwFormTemplateDetailVO systemField() {
        FlwFormTemplateDetailVO result = new FlwFormTemplateDetailVO();
        
        // 查询全部模块
        List<ContractModuleEntity> allModules = contractModuleMapper.selectList(new LambdaQueryWrapper<ContractModuleEntity>()
                .eq(ContractModuleEntity::getIsEnabled, true));
        
        if (CollectionUtils.isEmpty(allModules)) {
            result.setFormFields(new ArrayList<>());
            return result;
        }
        
        List<Integer> allModuleIds = allModules.stream().map(ContractModuleEntity::getId).collect(Collectors.toList());
        
        // 查询系统模块ID列表
        List<Integer> systemModuleIds = allModules.stream()
                .filter(module -> module.getIsSystem() != null && module.getIsSystem())
                .map(ContractModuleEntity::getId)
                .collect(Collectors.toList());
        
        // 查询全部模块下的字段关联
        List<ContractModuleFieldEntity> moduleFieldEntities = contractModuleFieldMapper.selectList(new LambdaQueryWrapper<ContractModuleFieldEntity>()
                .in(ContractModuleFieldEntity::getModuleId, allModuleIds));
        
        // 查询全部字段
        List<Long> allFieldIds = moduleFieldEntities.stream().map(ContractModuleFieldEntity::getFieldId).distinct().collect(Collectors.toList());
        List<ContractFieldEntity> allFields = contractFieldMapper.selectList(new LambdaQueryWrapper<ContractFieldEntity>()
                .in(ContractFieldEntity::getId, allFieldIds)
                .eq(ContractFieldEntity::getIsEnabled, true));
        
        // 创建启用字段配置（只对系统模块和系统字段设置为启用）
        List<ContractWorkflowFormFieldEntity> enabledFields = new ArrayList<>();
        Map<Integer, List<ContractModuleFieldEntity>> moduleFieldMap = moduleFieldEntities.stream()
                .collect(Collectors.groupingBy(ContractModuleFieldEntity::getModuleId));
        Map<Long, ContractFieldEntity> fieldMap = allFields.stream()
                .collect(Collectors.toMap(ContractFieldEntity::getId, field -> field));
        
        // 只为系统模块下的系统字段创建启用配置
        for (Integer moduleId : systemModuleIds) {
            List<ContractModuleFieldEntity> moduleFields = moduleFieldMap.getOrDefault(moduleId, List.of());
            for (ContractModuleFieldEntity moduleField : moduleFields) {
                ContractFieldEntity field = fieldMap.get(moduleField.getFieldId());
                if (field != null && field.getIsSystem() != null && field.getIsSystem()) {
                    ContractWorkflowFormFieldEntity formField = new ContractWorkflowFormFieldEntity();
                    formField.setModuleId(moduleId);
                    formField.setFieldId(field.getId());
                    formField.setIsEnabled(true);
                    formField.setIsRequired(field.getIsRequired());
                    formField.setIsHidden(false);
                    enabledFields.add(formField);
                }
            }
        }
        
        // 构造结果（传入全部模块和全部字段，但只有系统的会被设置为启用）
        result.setFormFields(buildFormFields(allModules, systemModuleIds, allFields, enabledFields));
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateByIdNew(FlwFormTemplateDetailVO flwFormTemplate) {
        if (null == flwFormTemplate || null == flwFormTemplate.getId()) {
            return false;
        }
        FlwFormTemplate template = this.getById(flwFormTemplate.getId());
        if (null == template) {
            return false;
        }
        BeanUtils.copyProperties(flwFormTemplate, template);
//        template.setContent(JSON.toJSONString(flwFormTemplate.getFormFields()));
        super.updateById(template);
        List<WorkflowFormFieldsListDTO> formFields = flwFormTemplate.getFormFields();
        // 保存模块关联
        contractWorkflowModuleMapper.delete(Wrappers.<ContractWorkflowModuleEntity>lambdaQuery()
                .eq(ContractWorkflowModuleEntity::getWorkflowId, template.getId()));
        // 保存字段关联
        if (!CollectionUtils.isEmpty(formFields)) {
            contractWorkflowFormFieldMapper.delete(Wrappers.<ContractWorkflowFormFieldEntity>lambdaQuery()
                    .eq(ContractWorkflowFormFieldEntity::getWorkflowId, flwFormTemplate.getId()));
            for (WorkflowFormFieldsListDTO formField : formFields) {
                if (formField.getIsEnabled()){
                    ContractWorkflowModuleEntity contractWorkflowModuleEntity = new ContractWorkflowModuleEntity();
                    contractWorkflowModuleEntity.setWorkflowId(template.getId());
                    contractWorkflowModuleEntity.setModuleId(formField.getId());
                    contractWorkflowModuleMapper.insert(contractWorkflowModuleEntity);
                }
                if (CollectionUtils.isEmpty(formField.getWorkflowFormFields())) {
                    continue;
                }
                List<WorkflowFormFieldDTO> workflowFormFields = formField.getWorkflowFormFields();
                for (WorkflowFormFieldDTO workflowFormField : workflowFormFields) {
                    saveField(formField, workflowFormField, template);
                }
            }
        }
        return true;
    }

    @Override
    public boolean addWorkflowModules(WorkflowModuleDTO workflowModuleDTO) {
        // 1. 验证流程是否存在
        FlwFormTemplate template = this.getById(workflowModuleDTO.getTemplateId());
        if (null == template) {
            return false;
        }

        // 3. 批量保存关联关系
        List<ContractWorkflowModuleEntity> workflowModules = workflowModuleDTO.getModuleIds().stream()
                .map(moduleId -> {
                    ContractWorkflowModuleEntity entity = new ContractWorkflowModuleEntity();
                    entity.setWorkflowId(workflowModuleDTO.getTemplateId());
                    entity.setModuleId(moduleId);
                    return entity;
                })
                .collect(Collectors.toList());

        contractWorkflowModuleMapper.insert(workflowModules);
        return true;
    }

    @Override
    public boolean deleteWorkflowModules(WorkflowModuleDTO workflowModuleDTO) {
        // 1. 验证流程是否存在
        FlwFormTemplate template = this.getById(workflowModuleDTO.getTemplateId());
        if (null == template) {
            return false;
        }

        // 2. 删除关联关系
        return contractWorkflowModuleMapper.delete(
                new LambdaQueryWrapper<ContractWorkflowModuleEntity>()
                        .eq(ContractWorkflowModuleEntity::getWorkflowId, workflowModuleDTO.getTemplateId())
                        .in(ContractWorkflowModuleEntity::getModuleId, workflowModuleDTO.getModuleIds())
        ) > 0;

    }

    private void saveField(WorkflowFormFieldsListDTO formField, WorkflowFormFieldDTO workflowFormField, FlwFormTemplate template) {
        ContractWorkflowFormFieldEntity formFieldEntity = new ContractWorkflowFormFieldEntity();
        formFieldEntity.setWorkflowId(template.getId());
        formFieldEntity.setModuleId(formField.getId());
        formFieldEntity.setFieldId(workflowFormField.getFieldId());
        formFieldEntity.setIsEnabled(workflowFormField.getIsEnabled());
        WorkflowFormFieldDTO.ConfigDetail configDetails = workflowFormField.getConfigDetails();
        if (null != configDetails) {
            formFieldEntity.setIsRequired(configDetails.getIsRequired());
            formFieldEntity.setPlaceholderText(configDetails.getPlaceholderText());
            formFieldEntity.setEmptyStateText(configDetails.getEmptyStateText());

            if (ObjectUtil.isNotNull(configDetails.getDefaultValue()) && configDetails.getDefaultValue() != "null") {

                if (configDetails.getDefaultValue() instanceof Map<?, ?>) {
                    Map<String, Object> map = (Map<String, Object>) configDetails.getDefaultValue();
                    formFieldEntity.setDefaultValue(JSON.toJSONString(map));
                } else if (configDetails.getDefaultValue() instanceof String) {
                    formFieldEntity.setDefaultValue((String) configDetails.getDefaultValue());
                } else if (configDetails.getDefaultValue() instanceof Integer) {
                    formFieldEntity.setDefaultValue(String.valueOf(configDetails.getDefaultValue()));
                }
            }
        }
        contractWorkflowFormFieldMapper.insert(formFieldEntity);
        if (CollectionUtils.isEmpty(workflowFormField.getChildFields())) {
            return;
        }
        for (WorkflowFormFieldDTO childField : workflowFormField.getChildFields()) {
            saveField(formField, childField, template);
        }
    }

    /**
     * 构建表单字段列表
     */
    private List<WorkflowFormFieldsListDTO> buildFormFields(List<ContractModuleEntity> allModules,
                                                            List<Integer> enabledModuleIds,
                                                            List<ContractFieldEntity> allFields,
                                                            List<ContractWorkflowFormFieldEntity> enabledFields) {

        // 构建字段ID到字段信息的映射
        Map<Long, ContractFieldEntity> fieldMap = allFields.stream()
                .collect(Collectors.toMap(ContractFieldEntity::getId, field -> field));

        // 构建启用字段的映射
        Map<String, ContractWorkflowFormFieldEntity> enabledFieldMap = enabledFields.stream()
                .collect(Collectors.toMap(field -> field.getFieldId() + "_" + field.getModuleId(), field -> field));

        // 获取模块字段关联
        List<ContractModuleFieldEntity> moduleFieldEntities = contractModuleFieldMapper.selectList(new LambdaQueryWrapper<ContractModuleFieldEntity>()
                .in(ContractModuleFieldEntity::getModuleId, allModules.stream().map(ContractModuleEntity::getId).collect(Collectors.toList())));
        Map<Integer, List<ContractModuleFieldEntity>> moduleFieldMap = moduleFieldEntities.stream()
                .collect(Collectors.groupingBy(ContractModuleFieldEntity::getModuleId));

        // 分离父字段和子字段
        Map<Long, List<ContractFieldEntity>> parentChildMap = allFields.stream()
                .filter(field -> field.getParentFieldId() != null)
                .collect(Collectors.groupingBy(ContractFieldEntity::getParentFieldId));

        // 对模块按moduleOrder排序
        allModules.sort(Comparator.comparing(ContractModuleEntity::getModuleOrder, Comparator.nullsLast(Comparator.naturalOrder())));

        // 构建返回结果
        List<WorkflowFormFieldsListDTO> result = allModules.stream().map(module -> {
            WorkflowFormFieldsListDTO moduleDTO = new WorkflowFormFieldsListDTO();
            moduleDTO.setId(module.getId());
            moduleDTO.setModuleName(module.getModuleName());
            moduleDTO.setModuleOrder(module.getModuleOrder());
            moduleDTO.setIsSystem(module.getIsSystem());
            moduleDTO.setIsEnabled(module.getIsSystem() || enabledModuleIds.contains(module.getId()));

            // 获取该模块下的字段关联，并按fieldOrder排序
            List<ContractModuleFieldEntity> moduleFields = new ArrayList<>(moduleFieldMap.getOrDefault(module.getId(), List.of()));
            // 按字段顺序排序
            moduleFields.sort(Comparator.comparing(ContractModuleFieldEntity::getFieldOrder, Comparator.nullsLast(Comparator.naturalOrder())));

            // 构建字段ID到模块字段关联的映射（用于获取字段顺序）
            Map<Long, ContractModuleFieldEntity> fieldToModuleFieldMap = moduleFields.stream()
                    .collect(Collectors.toMap(ContractModuleFieldEntity::getFieldId, mf -> mf));

            // 获取该模块下的所有父字段，并按fieldOrder排序
            List<ContractFieldEntity> parentFields = moduleFields.stream()
                    .map(mf -> fieldMap.get(mf.getFieldId()))
                    .filter(Objects::nonNull)
                    .filter(field -> field.getParentFieldId() == null)
                    .collect(Collectors.toList());

            // 构建字段DTO
            List<WorkflowFormFieldDTO> formFields = parentFields.stream().map(parentField -> {
                String parentKey = parentField.getId() + "_" + module.getId();
                ContractModuleFieldEntity parentModuleField = fieldToModuleFieldMap.get(parentField.getId());
                WorkflowFormFieldDTO parentDTO = convertToFormFieldDTO(parentField, enabledFieldMap.get(parentKey), parentModuleField);

                // 添加子字段
                List<ContractFieldEntity> children = parentChildMap.getOrDefault(parentField.getId(), List.of());
                if (!CollectionUtils.isEmpty(children)) {
                    // 过滤出属于当前模块的子字段，并按fieldOrder排序
                    List<WorkflowFormFieldDTO> childDTOs = children.stream()
                            .filter(child -> moduleFields.stream().anyMatch(mf -> mf.getFieldId().equals(child.getId())))
                            // 按字段顺序排序
                            .sorted((child1, child2) -> {
                                ContractModuleFieldEntity mf1 = fieldToModuleFieldMap.get(child1.getId());
                                ContractModuleFieldEntity mf2 = fieldToModuleFieldMap.get(child2.getId());
                                Integer order1 = mf1 != null ? mf1.getFieldOrder() : Integer.MAX_VALUE;
                                Integer order2 = mf2 != null ? mf2.getFieldOrder() : Integer.MAX_VALUE;
                                return Integer.compare(order1, order2);
                            })
                            .map(child -> {
                                String childKey = child.getId() + "_" + module.getId();
                                ContractModuleFieldEntity childModuleField = fieldToModuleFieldMap.get(child.getId());
                                return convertToFormFieldDTO(child, enabledFieldMap.get(childKey), childModuleField);
                            })
                            .collect(Collectors.toList());
                    parentDTO.setChildFields(childDTOs);
                }

                return parentDTO;
            }).collect(Collectors.toList());

            moduleDTO.setWorkflowFormFields(formFields);
            return moduleDTO;
        }).collect(Collectors.toList());

        return result;
    }

    /**
     * 转换字段实体为WorkflowFormFieldDTO
     */
    private WorkflowFormFieldDTO convertToFormFieldDTO(ContractFieldEntity field, ContractWorkflowFormFieldEntity formField, ContractModuleFieldEntity moduleField) {
        WorkflowFormFieldDTO dto = new WorkflowFormFieldDTO();
        BeanUtils.copyProperties(field, dto);

        if (field.getFieldOptions() != null) {
            dto.setFieldOptionsMap(JSON.parseObject(field.getFieldOptions(), Map.class));
        }
        dto.setFieldId(field.getId());
        dto.setId(null);
//        dto.setIsRequired(field.getIsRequired());
        dto.setIsEnabled(false);

        // 设置字段顺序
        if (moduleField != null) {
            dto.setFieldOrder(moduleField.getFieldOrder());
        }

        if (null != formField) {
            dto.setIsEnabled(formField.getIsEnabled());
            WorkflowFormFieldDTO.ConfigDetail configDetail = new WorkflowFormFieldDTO.ConfigDetail();
            configDetail.setIsRequired(formField.getIsRequired());
            configDetail.setPlaceholderText(formField.getPlaceholderText());
            configDetail.setEmptyStateText(formField.getEmptyStateText());
            if (JSONObject.isValidObject(formField.getDefaultValue())){
                configDetail.setDefaultValue(JSON.parseObject(formField.getDefaultValue()));
            }else {
                try {
                    configDetail.setDefaultValue(Integer.parseInt(formField.getDefaultValue()));
                }catch (Exception e) {
                    configDetail.setDefaultValue(formField.getDefaultValue());
                }
            }
            dto.setConfigDetails(configDetail);
        }

        return dto;
    }

    /**
     * 构造字段模板
     */
    private Map<String, Object> buildFieldTemplate() {
        return Arrays.stream(FieldTypeEnum.values()).collect(Collectors.toMap(
                FieldTypeEnum::getKey,
                item -> {
                    if (item.getValueScope() != null) {
                        return JSON.parseObject(item.getValueScope(), Map.class);
                    }
                    return item;
                }));
    }

    /**
     * 构建字段树节点
     */
    private List<FieldTreeDTO.FieldTreeNode> buildFieldTreeNode(Long parentFieldId, List<ContractFieldEntity> fieldEntities) {
        List<FieldTreeDTO.FieldTreeNode> fieldTreeNodes = fieldEntities.stream()
                .filter(item -> Objects.equals(item.getParentFieldId(), parentFieldId))
                .map(item -> {
                    FieldTreeDTO.FieldTreeNode fieldTreeNode = new FieldTreeDTO.FieldTreeNode();
                    fieldTreeNode.setFieldId(item.getId());
                    fieldTreeNode.setCode(item.getCode());
                    fieldTreeNode.setFieldName(item.getFieldName());
                    return fieldTreeNode;
                })
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(fieldTreeNodes)) {
            return null;
        } else {
            return fieldTreeNodes.stream()
                    .map(item -> {
                        item.setChildren(buildFieldTreeNode(item.getFieldId(), fieldEntities));
                        return item;
                    })
                    .collect(Collectors.toList());
        }
    }

    private boolean initField(Long id) {
        // 获取当前系统模块
        List<ContractModuleEntity> moduleEntities = contractModuleMapper.selectList(new LambdaQueryWrapper<ContractModuleEntity>()
                .eq(ContractModuleEntity::getIsSystem, true)
                .eq(ContractModuleEntity::getIsEnabled, true));
        List<Integer> moduleIds = moduleEntities.stream().map(ContractModuleEntity::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(moduleIds)) {
            return false;
        }
        // 保存模块关联关系
        for (Integer moduleId : moduleIds) {
            ContractWorkflowModuleEntity contractWorkflowModuleEntity = new ContractWorkflowModuleEntity();
            contractWorkflowModuleEntity.setWorkflowId(id);
            contractWorkflowModuleEntity.setModuleId(moduleId);
            contractWorkflowModuleMapper.insert(contractWorkflowModuleEntity);
        }
        // 获取模块下系统字段
        List<ContractModuleFieldEntity> moduleField = contractModuleFieldMapper.selectList(new LambdaQueryWrapper<ContractModuleFieldEntity>()
                .in(ContractModuleFieldEntity::getModuleId, moduleIds));
        List<Long> fieldIds = moduleField.stream().map(ContractModuleFieldEntity::getFieldId).distinct().collect(Collectors.toList());
        List<ContractFieldEntity> fieldEntities = contractFieldMapper.selectList(new LambdaQueryWrapper<ContractFieldEntity>()
                .in(ContractFieldEntity::getId, fieldIds)
                .eq(ContractFieldEntity::getIsSystem, true)
                .eq(ContractFieldEntity::getIsEnabled, true));
        Map<Long, ContractFieldEntity> fieldMap = fieldEntities.stream().collect(Collectors.toMap(ContractFieldEntity::getId, v -> v));
        Map<Integer, List<ContractModuleFieldEntity>> moduleFieldMap = moduleField.stream().collect(Collectors.groupingBy(ContractModuleFieldEntity::getModuleId));
        // 保存系统字段关联关系
        for (Integer moduleId : moduleIds) {
            if (!moduleFieldMap.containsKey(moduleId)) {
                continue;
            }
            List<ContractModuleFieldEntity> moduleFields = moduleFieldMap.get(moduleId);
            for (ContractModuleFieldEntity moduleFieldEntity : moduleFields) {
                if (!fieldMap.containsKey(moduleFieldEntity.getFieldId())) {
                    continue;
                }
                ContractFieldEntity field = fieldMap.get(moduleFieldEntity.getFieldId());
                ContractWorkflowFormFieldEntity contractWorkflowFormFieldEntity = new ContractWorkflowFormFieldEntity();
                contractWorkflowFormFieldEntity.setWorkflowId(id);
                contractWorkflowFormFieldEntity.setModuleId(moduleId);
                contractWorkflowFormFieldEntity.setFieldId(moduleFieldEntity.getFieldId());
                contractWorkflowFormFieldEntity.setIsRequired(field.getIsRequired());
                contractWorkflowFormFieldEntity.setIsHidden(false);
                contractWorkflowFormFieldEntity.setIsEnabled(true);
                contractWorkflowFormFieldEntity.setHelpDisplayType(DisplayTypeEnum.BUBBLE);
                contractWorkflowFormFieldMapper.insert(contractWorkflowFormFieldEntity);
            }
        }
        return true;
    }
}
